//////////////////////////////////////////////////////////////////////////
// FileName:UserFunctionsSet
// CreateBy:Fenky
// CreateDate:2009-07-16
// Description:
//		        Set User Access Functions Directly 
//      
// Modify Log:20100114:Add User Function Record Operate Scheme --DragonXiong
//            20100204:Init the GrantTree UserID for DataSetPermission Set --DragonXiong
//	
// Copyright:ASL-MIS
/////////////////////////////////////////////////////////////////////////

using System;
using System.Data;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Auto.Data.Security;
using BLL = Auto.Data.Systems.BLL;
using Auto.Data.Setting;
using Auto.Data.HumanResource;

namespace BaseSystem._System
{
    public partial class UserFunctionsSet : System.Web.UI.Page
    {

        /// <summary>
        /// Is Set User Function Or Is Set User Function DataSet Permission
        /// </summary>
        private string Action
        {
            get { return (ViewState["Action"] == null) ? "SetUserFunc" : ViewState["Action"].ToString(); }
            set { ViewState["Action"] = value; }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            UcrbRecordScheme1.EventSelected += new BaseSystem._System.UserControl.ucrbRecordScheme.SelectedEventHandler(UcrbRecordScheme1_EventSelected);
        }

        void UcrbRecordScheme1_EventSelected(string schemeID)
        {
            SetNodesRecordSchemeCheck();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitPage();
            }
        }

        #region Init Page
        private void InitPage()
        {

            GVUsers.Attributes.Add("SortExpression", "UserID");
            GVUsers.Attributes.Add("SortDirection", " ASC");
            BindGridView();

            BLL.Systems systems = new BLL.Systems();
            ddlSystems.DataSource = systems.GetSystems();
            ddlSystems.DataTextField = "SysName";
            ddlSystems.DataValueField = "SysID";

            ddlSystems.DataBind();

        }
        #endregion Init Page

        #region Data Bind


        private void BindGridView()
        {
            DataTable dt = new Auto.Data.Security.Users().GetDataByKey(this.txtUserID.Text, "", this.UcDivision1.DivID);
            string sortExpression = this.GVUsers.Attributes["SortExpression"];
            string sortDirection = this.GVUsers.Attributes["SortDirection"];
            if ((!string.IsNullOrEmpty(sortExpression)) && (!string.IsNullOrEmpty(sortDirection)))
            {
                dt.DefaultView.Sort = string.Format("{0} {1}", sortExpression, sortDirection);
            }
            GVUsers.DataSource = dt;
            GVUsers.DataBind();
        }

        #endregion Data Bind

        private void SetNodesCheck()
        {
            SysUserFunc sysUserFunc = new SysUserFunc();
            DataTable sysUserFuncs = new DataTable();
            try
            {
                sysUserFuncs = sysUserFunc.GetDataByKey(ddlSystems.SelectedValue, this.lblUserName.Text, "", " ");

            }
            catch (Exception ex)
            {
                throw ex;
            }

            IDictionary<string, string> checkedFuncNodes = new Dictionary<string, string>();
            foreach (DataRow dr in sysUserFuncs.Rows)
            {
                string key = dr[SysUserFunc.FIELD_FuncID].ToString();
                if (!checkedFuncNodes.ContainsKey(key))
                {
                    checkedFuncNodes.Add(key, dr[SysUserFunc.FIELD_FuncID].ToString());
                }
            }
            ucMenutree1.CheckedFuncNodes = checkedFuncNodes;


            IDictionary<string, string> checkedOperateNodes = new Dictionary<string, string>();
            if (sysUserFunc.SysUsersFuncOperates != null && sysUserFunc.SysUsersFuncOperates.Count > 0)
            {
                foreach (SysUsersFuncOperate funcOperate in sysUserFunc.SysUsersFuncOperates)
                {
                    string key = funcOperate.FuncID + "|" + funcOperate.OperateID;
                    if (!checkedOperateNodes.ContainsKey(key))
                    {
                        checkedOperateNodes.Add(key, funcOperate.OperateID);
                    }
                }
                ucMenutree1.CheckedOperateNodes = checkedOperateNodes;
            }

        }

        /// <summary>
        /// Checked the Operation and Function Nodes According the User Record Scheme in table _SysUserFuncROS
        /// </summary>
        private void SetNodesRecordSchemeCheck()
        {
            UcGranttree1.Clear();
            SysUserFuncROS sysUserFuncROS = new SysUserFuncROS();
            DataTable dtsysUserFuncRos = new DataTable();
            try
            {
                dtsysUserFuncRos = sysUserFuncROS.GetDataByKey(this.lblUserName.Text, ddlSystems.SelectedValue, "", UcrbRecordScheme1.SelectedValue, "");
            }
            catch (Exception ex)
            {
                throw ex;
            }

            IDictionary<string, string> checkedFuncNodes = new Dictionary<string, string>();
            foreach (DataRow dr in dtsysUserFuncRos.Rows)
            {
                string key = dr[SysUserFuncROS.FIELD_FuncID].ToString();
                if (!checkedFuncNodes.ContainsKey(key))
                {
                    checkedFuncNodes.Add(key, dr[SysUserFuncROS.FIELD_FuncID].ToString());
                }
            }
            UcGranttree1.CheckedFuncNodes = checkedFuncNodes;


            IDictionary<string, string> checkedOperateNodes = new Dictionary<string, string>();
            foreach (DataRow dr in dtsysUserFuncRos.Rows)
            {
                string key = dr[SysUserFuncROS.FIELD_FuncID].ToString() + "|" + dr[SysUserFuncROS.FIELD_OperateID].ToString();
                if (!checkedOperateNodes.ContainsKey(key))
                {
                    checkedOperateNodes.Add(key, dr[SysUserFuncROS.FIELD_OperateID].ToString());
                }
            }
            UcGranttree1.CheckedOperateNodes = checkedOperateNodes;


          
        }

        /// <summary>
        /// Get User Function Operation List
        /// </summary>
        /// <returns></returns>
        private List<SysUsersFuncOperate> GetSysUserFuncOperates()
        {
            List<SysUsersFuncOperate> listOperates = new List<SysUsersFuncOperate>();
            SysUsersFuncOperate sysUsersFuncOperate = null;
            foreach (KeyValuePair<string, string> checkedNode in this.ucMenutree1.CheckedOperateNodes)
            {
                string[] funcOperate = checkedNode.Key.Split('|');
                sysUsersFuncOperate = new SysUsersFuncOperate();
                sysUsersFuncOperate.FuncID = funcOperate[0];
                sysUsersFuncOperate.UserID = lblUserName.Text;
                sysUsersFuncOperate.SysID = ddlSystems.SelectedValue;
                sysUsersFuncOperate.OperateID = funcOperate[1];
                sysUsersFuncOperate.Note = checkedNode.Value;
                listOperates.Add(sysUsersFuncOperate);

            }
            return listOperates;
        }
        /// <summary>
        /// Get User Function Record Operation Scheme 
        /// </summary>
        /// <returns></returns>
        private List<SysUserFuncROS> GetSysUserFuncRecordOperates()
        {
            List<SysUserFuncROS> listRecodOperates = new List<SysUserFuncROS>();
            SysUserFuncROS recordOperates = null;
            foreach (KeyValuePair<string, string> checkedNode in this.UcGranttree1.CheckedOperateNodes)
            {
                string[] funcOperate = checkedNode.Key.Split('|');
                recordOperates = new SysUserFuncROS();
                recordOperates.UserID = lblUserName.Text;
                recordOperates.SysID = ddlSystems.SelectedValue;
                recordOperates.FuncID = funcOperate[0];
                recordOperates.SchemeID = UcrbRecordScheme1.SelectedValue;
                recordOperates.OperateID = funcOperate[1];
                recordOperates.RecAcct = "";
                recordOperates.RecDate = DateTime.Now;
                recordOperates.LastUpdateDate = DateTime.Now;
                recordOperates.UserAcct = "";
                listRecodOperates.Add(recordOperates);
            }
            return listRecodOperates;
        }
        #region Event
        protected void GVUsers_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int rowIndex = Convert.ToInt32(e.CommandArgument);
            System.Drawing.Color selectedbackcolor = System.Drawing.ColorTranslator.FromHtml("#d7e3f6");
            for (int i = 0; i < GVUsers.Rows.Count; i++)
            {
                if (i == rowIndex)
                {
                    GVUsers.Rows[i].BackColor = selectedbackcolor;
                }
                else
                {
                    GVUsers.Rows[i].BackColor = System.Drawing.Color.Empty;
                }
            }
            string userID = ((Label)GVUsers.Rows[rowIndex].FindControl("lblUserID")).Text; //GVUsers.Rows[rowIndex].Cells[3].Text;

            ucMenutree1.TreeInit(ddlSystems.SelectedValue, ddlSystems.SelectedItem.Text);
            tbRoles.Visible = true;
            this.lblUserName.Text = userID;
            switch (e.CommandName)
            {

                case "SetUserFunc":
                    lblUserFuncNote.Visible = true;
                    lblUserFuncDateSetNote.Visible = false;
                    //UcrbRecordScheme1.Visible = false;
                    trRecordScheme.Visible = false;
                    SetNodesCheck();
                    Action = "SetUserFunc";
                    TreeVisible(true);
                    break;
                case "SetUserFuncDataSet":
                    lblUserFuncNote.Visible = false;
                    lblUserFuncDateSetNote.Visible = true;
                    //UcrbRecordScheme1.Visible = true;
                    trRecordScheme.Visible = true;
                    UcrbRecordScheme1.InitControl();
                    //SetNodesRecordSchemeCheck();
                    Action = "SetUserFuncDataSet";
                    TreeVisible(false);
                    UcGranttree1.UserID = userID; //Set the User Selected
                    UcGranttree1.TreeInit(ddlSystems.SelectedValue, ddlSystems.SelectedItem.Text,true);
                    break;
            }


        }
        private void TreeVisible(bool isShowMenutree)
        {
            this.ucMenutree1.Visible = isShowMenutree;
            this.UcGranttree1.Visible = !isShowMenutree;
        }
        protected void GVUsers_Sorting(object sender, GridViewSortEventArgs e)
        {
            string sortExpress = e.SortExpression.ToString();
            string sortDirection = this.GVUsers.Attributes["SortDirection"].ToString();
            GVUsers.Attributes["SortExpression"] = sortExpress;
            GVUsers.Attributes["SortDirection"] = sortDirection == " DESC" ? " ASC" : " DESC";


            BindGridView();
        }

        protected void lkbtnOK_Click(object sender, EventArgs e)
        {
            if (Action == "SetUserFunc")
            {
                IList<SysUserFunc> sysUserFuncs = new List<SysUserFunc>();

                SysUserFunc func = null;
                IDictionary<string, string> checkNodes = ucMenutree1.CheckedFuncNodes;
                foreach (KeyValuePair<string, string> keyValue in checkNodes)
                {
                    func = new SysUserFunc();
                    func.FuncID = keyValue.Key;
                    func.SysID = ddlSystems.SelectedValue;
                    func.UserID = lblUserName.Text;
                    func.GrantUserID = "";
                    sysUserFuncs.Add(func);
                }
                func = new SysUserFunc();
                func.SysID = ddlSystems.SelectedValue;
                func.UserID = lblUserName.Text;
                func.SysUsersFuncOperates = GetSysUserFuncOperates();
                func.SysUserFuncs = sysUserFuncs;
                func.Insert();
            }

            if (Action == "SetUserFuncDataSet")
            {
                //SysUserFuncROS userfuncROS = new SysUserFuncROS();
                //IDictionary<string, string> checkNodes = ucUserFunctionsSet.CheckedFuncNodes;
                //foreach (KeyValuePair<string, string> keyValue in checkNodes)
                //{
                //    userfuncROS.UserID = lblUserName.Text;
                //    userfuncROS.SysID = ddlSystems.SelectedValue;
                //    userfuncROS.FuncID = keyValue.Key;
                //}
                SysUserFuncROS userfuncROS = new SysUserFuncROS(lblUserName.Text, ddlSystems.SelectedValue, "", UcrbRecordScheme1.SelectedValue, ""); ;
                userfuncROS.SysUserFuncROSList=GetSysUserFuncRecordOperates();
                userfuncROS.Insert();
            }


            this.tbRoles.Visible = false;
        }


        protected void lkbtnCancel_Click(object sender, EventArgs e)
        {
            this.tbRoles.Visible = false;
        }

        protected void ddlDiv_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindGridView();
        }
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindGridView();
        }

        protected void ddlEmpID_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindGridView();
        }
        #endregion Event
    }
}